package com.qf.web.controller;

import cn.dsna.util.images.ValidateCode;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.qf.domain.Address;
import com.qf.domain.Order;
import com.qf.domain.User;
import com.qf.service.AddressService;
import com.qf.service.CartService;
import com.qf.service.UserService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.CartServiceImpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;
import com.qf.utils.MD5Util;
import com.qf.utils.RandomUtil;
import com.qf.utils.StringUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/userservlet")
public class UserServlet extends BaseServlet{
    public String checkUserName (HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        System.out.println("username = " + username);
        if(StringUtil.isEmpty(username)){
            response.getWriter().write("1");
            return null;
        }
        UserService userService=new UserServiceImpl();
        boolean b=userService.checkUserName(username);
        if(b){
            response.getWriter().write("1");//1不可用
            return null;
        }
        response.getWriter().write("0");//0用户不存在 可以使用
        return null;
    }

    public String register (HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        if(StringUtil.isEmpty(username)){
            request.setAttribute("msg","用户名不能为空");
            return "/register.jsp";
        }
        if(StringUtil.isEmpty(password)){
            request.setAttribute("msg","密码不能为空");
            return "/register.jsp";
        }
        if(StringUtil.isEmpty(repassword)){
            request.setAttribute("msg","确认密码不能为空");
            return "/register.jsp";
        }
        if(!password.equalsIgnoreCase(repassword)){
            request.setAttribute("msg","两次密码不一致");
            return "/register.jsp";
        }
        if(StringUtil.isEmpty(email)){
            request.setAttribute("msg","邮箱不能为空");
            return "/register.jsp";
        }

        UserService userService=new UserServiceImpl();
        boolean b = userService.checkUserName(username);
        if(b){
            request.setAttribute("msg","用户名已存在");
            return "/register.jsp";
        }

        User user=new User(null,username,password,email,gender, 1,1, RandomUtil.createActiveCode());
        try {
            userService.register(user);
            return "redirect:/registerSuccess.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","注册失败");
            return "/register.jsp";
        }
    }

    public String code (HttpServletRequest request, HttpServletResponse response) throws IOException {
        //String vcode = request.getParameter("vcode");
        ValidateCode validateCode=new ValidateCode(100,28,4,20);
        String validateCodeCode = validateCode.getCode();
        request.getSession().setAttribute("vcode", validateCodeCode);
        System.out.println("验证码 = " + validateCodeCode);

        validateCode.write(response.getOutputStream());
        return null;
    }

    public String login (HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");
        String auto = request.getParameter("auto");

        if(StringUtil.isEmpty(username)){
            request.setAttribute("msg", "用户名不能为空");
            return "/message.jsp";
        }
        if(StringUtil.isEmpty(password)){
            request.setAttribute("msg", "密码不能为空");
            return "/message.jsp";
        }
        if(StringUtil.isEmpty(vcode)){
            request.setAttribute("msg", "验证码不能为空");
            return "/message.jsp";
        }
        String  vcode1 = (String) request.getSession().getAttribute("vcode");
        if(!vcode.equalsIgnoreCase(vcode1)){
            request.setAttribute("msg", "验证码输入错误");
            return "/message.jsp";
        }

        UserService userService=new UserServiceImpl();
        try {
            User user=userService.login(username,password);
            request.getSession().setAttribute("user", user);

            if(auto!=null){
                System.out.println("auto = " + auto);
                String userInfo=username+"&"+password;
                userInfo = Base64Utils.encode(userInfo);

                Cookie cookie=new Cookie("userInfo",userInfo);
                cookie.setPath(request.getContextPath());
                cookie.setMaxAge(14*24*60*60);
                cookie.setHttpOnly(true);
                response.addCookie(cookie);
            }

            return "redirect:/index.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "登录失败"+e.getMessage());
            return "/message.jsp";
        }
    }

    public String logOut (HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session =request.getSession();
        session.removeAttribute("user");
        session.invalidate();

        Cookie cookie=new Cookie("userInfo","");
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/index.jsp";
    }


    //-----------------------------------------------------address-----------------------------------------------------

    //http://localhost:8080/userservlet?method=addAddress
    public String addAddress (HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user= (User) request.getSession().getAttribute("user");
        if(user == null){
            return "redirect:/login.jsp";
        }

        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");

        if(StringUtil.isEmpty(name)){
            request.setAttribute("msg", "收货人不能为空");
            return "/message.jsp";
        }
        if(StringUtil.isEmpty(phone)){
            request.setAttribute("msg", "收货人电话不能为空");
            return "/message.jsp";
        }
        if(StringUtil.isEmpty(detail)){
            request.setAttribute("msg", "收货人地址不能为空");
            return "/message.jsp";
        }

        try {
            AddressService addressService=new AddressServiceImpl();
            Address address =new Address(0,detail,name,phone,user.getId(),0);
            addressService.insertAddress(address);
            return "redirect:/userservlet?method=getAddress";
            //return "redirect:/address_info.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "增加地址失败"+e.getMessage());
            return "/address_info.jsp";
        }
    }

    //http://localhost:8080/userservlet?method=getAddress
    public String getAddress (HttpServletRequest request, HttpServletResponse response) {
        User user= (User) request.getSession().getAttribute("user");
        if(user == null){
            return "redirect:/login.jsp";
        }

        try {
            AddressService addressService=new AddressServiceImpl();
            List<Address> addressList = addressService.selectByUserId(user.getId());
            request.setAttribute("addList", addressList);
            return "/address_info.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "查询地址失败"+e.getMessage());
            return "/message.jsp";
        }
    }


    //http://localhost:8080/userservlet?method=deleteAddress&id=8
    public String deleteAddress (HttpServletRequest request, HttpServletResponse response) {
        User user= (User) request.getSession().getAttribute("user");
        if(user == null){
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");
        if(StringUtil.isEmpty(id)){
            request.setAttribute("msg","地址编号不能为空" );
            return "/message.jsp";
        }
        try {
            AddressService addressService=new AddressServiceImpl();
            addressService.deleteById(user.getId(),Integer.parseInt(id));
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","删除地址失败" +e.getMessage());
            return "/message.jsp";
        }
    }


    //http://localhost:8080/userservlet?method=defaultAddress&id=10
    public String defaultAddress (HttpServletRequest request, HttpServletResponse response) {
        User user= (User) request.getSession().getAttribute("user");
        if(user==null){
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");

        try {
            AddressService addressService=new AddressServiceImpl();
            addressService.setDefault(user.getId(),Integer.parseInt(id));
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","设置默认地址失败" +e.getMessage());
            return "/message.jsp";
        }
    }

    //http://localhost:8080/userservlet?method=updateAddress
    public String updateAddress (HttpServletRequest request, HttpServletResponse response) {
        User user= (User) request.getSession().getAttribute("user");
        if(user == null){
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");
        String level = request.getParameter("level");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        if(StringUtil.isEmpty(id)){
            request.setAttribute("msg", "地址编号为空");
            return "/message.jsp";
        }

        if(StringUtil.isEmpty(name)){
            request.setAttribute("msg","收货人不能为空" );
            return "/message.jsp";
        }
        if(StringUtil.isEmpty(phone)){
            request.setAttribute("msg","收货人电话不能为空" );
            return "/message.jsp";
        }
        if(StringUtil.isEmpty(detail)){
            request.setAttribute("msg","收货人地址不能为空" );
            return "/message.jsp";
        }

        try {
            AddressService addressService=new AddressServiceImpl();
            Address address=new Address(Integer.parseInt(id),detail,name,phone,user.getId(),Integer.parseInt(level));
            addressService.updateAddress(address);
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "修改地址信息失败"+e.getMessage());
            return "/message.jsp";
        }
    }

    //<a href="/userservlet?method=findUserDetail" >修改</a>
    public String findUserDetail (HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        try {
            UserService userService=new UserServiceImpl();
            User user = userService.selectByUId(Integer.parseInt(id));
            request.setAttribute("user", user);
            return "/UserDetail.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "修改地址信息失败"+e.getMessage());
            return "/message.jsp";
        }
    }

    //http://localhost:8080/userservlet?method=updateUserDetail
    public String updateUserDetail (HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        //String password = request.getParameter("password");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");

        try {
            UserService userService=new UserServiceImpl();
            userService.updateUserById(id,username,email,gender);
            return "/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "修改用户信息失败"+e.getMessage());
            return "/message.jsp";
        }
    }

//------------------------------------------------后台------------------------------------------------------


    //userservlet?method=adminLogin
    public String adminLogin (HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //password= MD5Util.md5(password);
        if(StringUtil.isEmpty(username)){
            request.setAttribute("msg", "用户名不能为空");
            return "/admin/message.jsp";
        }
        if(StringUtil.isEmpty(password)){
            request.setAttribute("msg", "密码不能为空");
            return "/admin/message.jsp";
        }
        try {
            UserService userService=new UserServiceImpl();
            User login = userService.login(username, password);
            request.setAttribute("admin", login);
            return "/admin/admin.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "后台登录失败"+e.getMessage());
            return "/admin/message.jsp";
        }
    }

    //userservlet?method=getUserList",
    public String getUserList (HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        //System.out.println("username = " + username);
        String gender = request.getParameter("gender");
        List<Object> params=new ArrayList<>();
        StringBuilder where =new StringBuilder(" where 1=1 ");
        if(!StringUtil.isEmpty(username)){
            where.append("  AND `username` LIKE ? ");
            params.add("%"+username+"%");
        }
        if(!StringUtil.isEmpty(gender)){
            where.append("  AND `gender`=? ");
            params.add(gender);
        }
        try {
            UserService userService=new UserServiceImpl();
            //List<User> userList=userService.selectByRole();
            List<User>userList=userService.selectByNameAndGender(where.toString(),params);
            if (userList != null && userList.size()>0){
                String josn = JSON.toJSONString(userList);
                System.out.println(josn);
                response.getWriter().write(josn);
            }
            //System.out.println("userList = " + userList);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "后台查询失败"+e.getMessage());
            return "/admin/message.jsp";
        }
    }



    //userservlet?method=updateUser&id="+id,
    public String updateUser (HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        //System.out.println("id = " + id);
        if(StringUtils.isEmpty(id)){
            request.setAttribute("msg", "用户id不能为空");
            return "/admin/message.jsp";
        }
        try {

            int uid = Integer.parseInt(id);
            //AddressService addressService=new AddressServiceImpl();
            //addressService.deleteByUId(uid);
            //CartService cartService=new CartServiceImpl();
            //cartService.deleteByUId(uid);
            UserService userService=new UserServiceImpl();
            //userService.deleteById(uid);
            userService.updateFlag0ById(uid);
            //userService.shanchuyonghu(uid);
            return "redirect:/userservlet?method=getUserList";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "后台删除失败"+e.getMessage());
            return "/admin/message.jsp";
        }
    }

    //userservlet?method=deleteUser?id="+id,
    public String deleteUser (HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        //System.out.println("id = " + id);
        if(StringUtils.isEmpty(id)){
            request.setAttribute("msg", "用户id不能为空");
            return "/admin/message.jsp";
        }
        try {

            int uid = Integer.parseInt(id);
            //AddressService addressService=new AddressServiceImpl();
            //addressService.deleteByUId(uid);
            //CartService cartService=new CartServiceImpl();
            //cartService.deleteByUId(uid);
            UserService userService=new UserServiceImpl();
            System.out.println("uid = " + uid);
            userService.deleteById(uid);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "后台删除失败"+e.getMessage());
            return "/admin/message.jsp";
        }
    }


    //userservlet?method=adminOut 退出登录
    public String adminOut (HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        session.invalidate();
        Cookie cookie = new Cookie("user", "");
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        return "redirect:/admin/login.jsp";

    }



//    ------------------------------------非会员--------------------------------------------------------------------------


//    /userservlet?method=getNoUserList",
    //userservlet?method=getNoUserList&username="+username+"&gender="+gender,
    public String getNoUserList (HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        System.out.println("username = " + username);
        String gender = request.getParameter("gender");
        List<Object> params=new ArrayList<>();
        StringBuilder where =new StringBuilder(" where 1=1 ");
        if(!StringUtil.isEmpty(username)){
            where.append("  AND `username` LIKE ? ");
            params.add("%"+username+"%");
        }
        if(!StringUtil.isEmpty(gender)){
            where.append("  AND `gender`=? ");
            params.add(gender);
        }
        try {
            UserService userService=new UserServiceImpl();
            //List<User> userList=userService.selectByRole();
            List<User>userList=userService.selectNoByNameAndGender(where.toString(),params);
            if (userList != null && userList.size()>0){
                String josn = JSON.toJSONString(userList);
                System.out.println(josn);
                response.getWriter().write(josn);
            }
            //System.out.println("userList = " + userList);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "后台查询失败"+e.getMessage());
            return "/admin/message.jsp";
        }
    }


    //userservlet?method=addNoUser&id="+id,
    public String addNoUser (HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id");
        //System.out.println("id = " + id);
        if(StringUtils.isEmpty(id)){
            request.setAttribute("msg", "用户id不能为空");
            return "/admin/message.jsp";
        }
        try {

            int uid = Integer.parseInt(id);
            UserService userService=new UserServiceImpl();
            //userService.deleteById(uid);
            userService.updateFlag1ById(uid);
            return "redirect:/userservlet?method=getNoUserList";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "后台删除失败"+e.getMessage());
            return "/admin/message.jsp";
        }
    }


    ///userservlet?method=deleteNoUser&id="+id,
    public String deleteNoUser (HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        String id = request.getParameter("id");
        System.out.println("id = " + id);
        if(StringUtils.isEmpty(id)){
            request.setAttribute("msg", "用户id不能为空");
            return "/admin/message.jsp";
        }
        try {

            int uid = Integer.parseInt(id);
            System.out.println("uid = " + uid);
            UserService userService=new UserServiceImpl();
            userService.deleteById(uid);
            return "redirect:/userservlet?method=getNoUserList";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "后台删除失败"+e.getMessage());
            return "/admin/message.jsp";
        }
    }

}
